package cn.dogger.easyboot.druid.config;

import cn.dogger.easyboot.druid.enums.DataSourceEnum;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.Map;

/**
 * 动态数据源
 */
public class DynamicDataSource extends AbstractRoutingDataSource {
    //线程内部的存储类
    private static final ThreadLocal<DataSourceEnum> contextHolder = new ThreadLocal();

    /**
     * 配置DataSource, defaultTargetDataSource为主数据源
     */
    public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) {
        //主数据源
        super.setDefaultTargetDataSource(defaultTargetDataSource);
        //多数据源map
        super.setTargetDataSources(targetDataSources);
        super.afterPropertiesSet();
    }

    //选择数据源
    @Override
    protected Object determineCurrentLookupKey() {
        return getDataSource();
    }

    public static void setDataSource(DataSourceEnum dataSource) {
        contextHolder.set(dataSource);
    }

    public static DataSourceEnum getDataSource() {
        return contextHolder.get();
    }

    //清空数据源选择,恢复默认值
    public static void clearDataSource() {
        contextHolder.remove();
    }
}
